import { defineStore } from 'pinia';
// import { asyncRoutes, constantRoutes } from '@/router';
import router from '@/router';

function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

function filterAsyncRoutes(routes, roles) {
  const res = [];

  routes.forEach(route => {
    const tmp = { ...route };
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });

  return res;
}

const isRouteExists = (path) => {
  return router.getRoutes().some(route => route.path === path);
};

const removeRoutes = (routes) => {
  routes.forEach(route => {
    if (isRouteExists(route.path)) {
      router.removeRoute(route.name);
    }
  });
};

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],       // 完整路由表
    addRoutes: [],     // 动态添加的路由表
    roles: JSON.parse(localStorage.getItem('roles') || '[]'), // 从 localStorage 中加载 roles
  }),
  actions: {
    SET_ROUTES(routes) {
      // 清除旧的动态路由
      removeRoutes(this.addRoutes);

      this.addRoutes = routes;
      this.routes = constantRoutes.concat(routes);

      // 添加新的动态路由
      routes.forEach(route => {
        if (!isRouteExists(route.path)) {
          router.addRoute(route); // 动态添加路由
        }
      });
    },
    generateRoutes(roles) {
      return new Promise(resolve => {
        let accessedRoutes;
        if (roles.includes('admin')) {
          accessedRoutes = asyncRoutes || [];
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
        }

        console.log('打印过滤后的路由', accessedRoutes); // 打印过滤后的路由
        this.SET_ROUTES(accessedRoutes);

        // 保存 roles 到 localStorage
        this.roles = roles;
        localStorage.setItem('roles', JSON.stringify(roles));

        resolve(accessedRoutes);
      });
    },
    clearRoles() {
      this.roles = [];
      localStorage.removeItem('roles'); // 清除 localStorage 中的 roles
    }
  }
});
